<?php

namespace app\result;

use app\model\extend\PCashbookUser;
use app\model\SysStatistics;
use app\model\user\Cashflows;
use app\model\user\Categories;
use app\model\user\User;
use think\Db;
use think\facade\Cache;

class StatisticResult extends BaseResult
{

    private function sys_statistics_data()
    {
        $model = new SysStatistics();
        $startDate = date('Y-m-d', strtotime("-1 month"));
        $data = $model->data_list_nopage([['date', '>=', $startDate]], '*', 'date asc');
        $legendData = [
            ['name' => '注册用户量(个)', 'field' => 'reg_user_count'],
            ['name' => '活跃用户量(个)', 'field' => 'active_user_count'],
            ['name' => '记账笔数(笔)', 'field' => 'amount_count'],
            ['name' => '记账总金额(元)', 'field' => 'amount_total'],
            ['name' => '记账总收入金额(元)', 'field' => 'amount_in'],
            ['name' => '记账总支出金额(元)', 'field' => 'amount_out'],
            ['name' => '接口访问次数（次）', 'field' => 'api_count'],
        ];
        $series = [];
        $category = array_column($data, 'date');

        foreach ($legendData as $item) {
            $series[] = [
                'data' => array_column($data, $item['field']),
                'name' => $item['name'],
                'type' => 'line',
                'smooth' => true
            ];
        }

        //按月统计
        $dataFormat = [
            'title' => [
                'text' => '系统统计信息',
                'subtext' => ''
            ],
            'tooltip' => [
                'trigger' => 'axis'
            ],
            'legend' => [
                'data' => $legendData
            ],
            'xAxis' => [
                'type' => 'category',
                'data' => $category
            ],
            'yAxis' => [
                'type' => 'value',
            ],
            'series' => $series
        ];

        return $dataFormat;

    }


    //最近30天用户增加数据
    private function user_data()
    {
        $model = new User();
        $table = $model->getTable();
        $stime = date('Y-m-d H:i:s', strtotime("-1 month"));
        $data = \think\facade\Db::query("SELECT count(*) as total,DATE_FORMAT(created_at,'%m-%d') as day_str from `" . $table . "` "
            . " where created_at >= '" . $stime . "' "
            . " GROUP BY day_str "
            . " order by created_at asc");


        $category = [];
        $data_list = [];
        if ($data) {
            foreach ($data as $item) {
                $category[] = $item['day_str'];
                $data_list[] = $item['total'];
            }
        }


        //按月统计
        $data_month = [
            'title' => [
                'text' => '账号注册数量',
                'subtext' => '单位：个'
            ],
            'tooltip' => [
                'trigger' => 'axis'
            ],
            'legend' => [
                'data' => ['注册量']
            ],
            'xAxis' => [
                'type' => 'category',
                'data' => $category
            ],
            'yAxis' => [
                'type' => 'value',
            ],
            'series' => [
                [
                    'data' => $data_list,
                    'name' => '注册量',
                    'type' => 'line',
                    'smooth' => true
                ]
            ]
        ];

        return $data_month;

    }

    //按月统计账单
    private function get_month_data()
    {

        $model = new Cashflows();
        //记账量按月份
        /* $month_list = [];
        $dataAmount = [];
        //最近12个月
       for ($i = 11; $i >= 0; $i--) {
            $month = date("Y-m", strtotime("-$i month"));
            $month_list[] = $month;
            $amount = $model->data_sum([
                'year' => date("Y", strtotime($month)),
                'month' => intval(date("m", strtotime($month)))
            ], 'amount');
            $dataAmount[] = max($amount, 0.00);

        }*/
        $table = $model->getTable();
        $stime = date('Y-m-d', strtotime("-12 month"));
        $data = \think\facade\Db::query("SELECT sum(amount) as total,DATE_FORMAT(`date`,'%Y-%m') as month_str from `" . $table . "` "
            . " where `date` >= '" . $stime . "' "
            . " GROUP BY month_str "
            . " order by date asc");
        if ($data) {
            foreach ($data as $item) {
                $category[] = $item['month_str'];
                $data_list[] = $item['total'];
            }
        }
        //按月统计
        $data_month = [
            'title' => [
                'text' => '记账量',
                'subtext' => '单位：元'
            ],
            'tooltip' => [
                'trigger' => 'axis'
            ],
            'legend' => [
                'data' => ['记账量']
            ],
            'xAxis' => [
                'type' => 'category',
                'data' => $category ?? []
            ],
            'yAxis' => [
                'type' => 'value'
            ],
            'series' => [
                [
                    'data' => $data_list ?? [],
                    'name' => '记账量',
                    'type' => 'line',
                    'smooth' => true
                ]
            ]
        ];

        return $data_month;
    }

    //后台数据统计
    public function getAdminStatistic($args = []): array
    {
        $month_data = $this->get_month_data();
        $pie_data = [];
        $model = new Cashflows();
        $pie_data[] = [
            'name' => '￥总支出流水',
            'value' => $model->data_sum(['type' => 20], 'amount'),
        ];
        $pie_data[] = [
            'name' => '￥总收入流水',
            'value' => $model->data_sum(['type' => 10], 'amount'),
        ];

        $pie = [
            'title' => [
                'text' => '支出类别统计',
                'subtext' => '单位：元'
            ],
            'tooltip' => [
                'trigger' => 'item',
                'formatter' => "{a} <br/>{b} : {c} ({d}%)"
            ],
            'legend' => [
                'orient' => 'vertical',
                'left' => 'right'
            ],

            'series' => [
                [
                    'name' => '支出类别统计',
                    'type' => 'pie',
                    'radius' => '50%',
                    'data' => $pie_data,
                    'label' => [
                        'show' => true,
                        'formatter' => '{b} : {c} ({d}%)'
                    ],
                    'labelLine' => [
                        'show' => true
                    ],
                    'emphasis' => [
                        'itemStyle' => [
                            'shadowBlur' => 10,
                            'shadowOffsetX' => 0,
                            'shadowColor' => 'rgba(0, 0, 0, 0.5)'
                        ]
                    ]
                ]
            ]
        ];
        $userData = $this->user_data();
        $data = [
            ['option' => $month_data, 'name' => '按月统计'],
            ['option' => $pie, 'name' => '支出类别统计'],
            ['option' => $this->sys_statistics_data(), 'name' => '系统统计信息'],
            ['option' => $userData, 'name' => '用户注册统计'],
        ];


        return self::success_return('success', $data);

    }

    public function setting_set($user_id, $args)
    {
        $data = $args['list'] ?? [];
        if (!$data) {
            return self::error_return('请选择要设置的项');
        }
        $list = [];
        foreach ($data as $item) {
            $list[] = [
                'key' => $item['key'],
                'label' => $item['label'],
                'value' => boolval($item['value'])
            ];
        }
        UserSettingResult::action($user_id, 'statistic_setting', $list);
        return self::success_return('保存成功', $list);
    }

    public function setting_get($user_id, $source = false)
    {
        $baseSet = [
            ['key' => 'pie', 'label' => '分类统计图', 'value' => true],
            ['key' => 'bar', 'label' => '收入支出对比图', 'value' => true],
            ['key' => 'line', 'label' => '收入支出趋势图', 'value' => true],
            ['key' => 'amount_type', 'label' => '收支类型饼图', 'value' => true],
        ];
        $value = UserSettingResult::get($user_id, 'statistic_setting');
        if (!$value) {
            UserSettingResult::action($user_id, 'statistic_setting', $baseSet);
        } else {
            if (count($value) !== count($baseSet)) {
                $baseSet = array_column($baseSet, null, 'key');
                $valueKeys = array_column($value, 'key');
                foreach ($baseSet as $key => $item) {
                    if (!in_array($key, $valueKeys)) {
                        $value[] = $item;
                    }
                }
                UserSettingResult::action($user_id, 'statistic_setting', $value);
            }
        }
        $value = UserSettingResult::get($user_id, 'statistic_setting');
        if ($source) {
            return $value;
        }
        return self::success_return('success', [
            'list' => $value
        ]);
    }

    //获取用户统计数据
    public function get_user_statistic($user_id, $args): array
    {
        $type = intval($args['type'] ?? '10');
        $query_type = trim($args['query_type'] ?? "month");
        $year = intval($args['year'] ?? date("Y"));
        $month = intval($args['month'] ?? date("m"));

        $where = [
            'user_id' => $user_id,
            'type' => $type,
        ];
        if ($query_type == 'month') {
            $where['year'] = $year;
            $where['month'] = $month;
        } elseif ($query_type == 'year') {
            $where['year'] = $year;
        }

        $setting = $this->setting_get($user_id, true);
        $setting = array_column($setting, null, 'key');
        $ckey = 'statistic_' . $user_id . '_' . $type . '_' . $query_type . '_' . $year . '_' . $month . md5(json_encode($setting));
        $cache = Cache::get($ckey);
        if ($cache) {
            return self::success_return('success', $cache);
        }

        if ($setting['bar']['value']) {
            $bar = $this->get_bar_data($where, $query_type);
        }
        if ($setting['line']['value']) {
            $lineData = $this->get_line_data($where, $query_type);
        }
        if ($setting['pie']['value']) {
            $pie = $this->get_pie_data($where);
        }
        if ($setting['amount_type']['value']) {
            $amount_type_pie = $this->get_pie_amount_type_data($where);
        }

        $list = [];
        if (!empty($pie['show'])) {
            $list[] = [
                'name' => '分类统计饼图',
                'type' => $pie['type'],
                'options' => $pie['option'],
                'chart_data' => [
                    'series' => $pie['series'],
                ]
            ];
        }
        if (!empty($bar['show'])) {
            $list[] = [
                'name' => '收支对比',
                'type' => $bar['type'],
                'options' => $bar['option'],
                'chart_data' => [
                    'categories' => $bar['categories'],
                    'series' => $bar['series'],
                ]
            ];
        }
        if (!empty($lineData['show'])) {
            $list[] = [
                'name' => '收支趋势',
                'type' => $lineData['type'],
                'options' => $lineData['option'],
                'chart_data' => $lineData['chartData']
            ];
        }
        if (!empty($amount_type_pie['show'])) {
            $list[] = [
                'name' => '收支类型统计饼图',
                'type' => $amount_type_pie['type'],
                'options' => $amount_type_pie['option'],
                'chart_data' => [
                    'series' => $amount_type_pie['series'],
                ]
            ];
        }
        Cache::set($ckey, [
            'list' => $list
        ], 2);

        return self::success_return('success', [
            'list' => $list
        ]);

    }

    //获取收入支出条形图
    private function get_bar_data($where, $query_type)
    {
        unset($where['type']);
        $model = new Cashflows();
        $categories = [];
        $series = [
            ['name' => '收入', 'data' => []],
            ['name' => '支出', 'data' => []]
        ];
        $data = $model->data_list_nopage($where, 'amount,type,date,month', 'date asc');
        if (!$data) {
            return [];
        }
        $format = [];
        foreach ($data as $value) {
            if ($query_type == 'month') {
                $ftype = $value['date'];
            } else {
                $ftype = $value['month'];
            }
            if (!isset($format[$ftype][$value['type']])) {
                $format[$ftype][$value['type']] = 0;
            }
            $format[$ftype][$value['type']] += $value['amount'];
            $format[$ftype][$value['type']] = round($format[$ftype][$value['type']], 2);
        }
        foreach ($format as $key => $item) {
            if ($query_type == 'month') {
                $categories[] = date('d日', strtotime($key));
                $series[0]['data'][] = $item[10] ?? 0;
                $series[1]['data'][] = $item[20] ?? 0;
            } else {
                $categories[] = $key . '月';
                $series[0]['data'][] = $item[10] ?? 0;
                $series[1]['data'][] = $item[20] ?? 0;
            }
        }


        $option = [
            'update' => true,
            'enableScroll' => true,
            'legend' => [],
            'xAxis' => [
                'disableGrid' => true,
                'type' => 'grid',
                'gridType' => 'dash',
                'itemCount' => 5,//x轴单屏显示数据的数量，默认为5个
                'scrollShow' => true,//新增是否显示滚动条，默认false
                'scrollAlign' => 'left',//滚动条初始位置
                'scrollBackgroundColor' => '#F7F7FF',//默认为 #EFEBEF
                'scrollColor' => '#DEE7F7',//默认为 #A6A6A6
            ],
            'yAxis' => [
                'showTitle' => true,
                'padding' => 10,
                'data' => [
                    ['title' => '收支情况', 'min' => 0]
                ]
            ],
            'extra' => [
                'column' => [
                    'type' => "stack",
                    'width' => 30,
                    'activeBgColor' => "#000000",
                    'activeBgOpacity' => 0.08,
                    'labelPosition' => "center"
                ],

            ],

        ];

        return [
            'show' => !empty($categories),
            'option' => $option,
            'type' => 'column',
            'categories' => $categories,
            'series' => $series
        ];
    }

    //分类统计饼图
    private function get_pie_data($where)
    {
        $model = new Cashflows();
        $data = $model->data_list_nopage($where, 'sum(amount) as amount,category_id', '', 'category_id');
        $result = [];
        if ($data) {
            $modelCategory = new Categories();
            foreach ($data as $item) {
                $category_name = $modelCategory->get_value(['id' => $item['category_id']], 'name');
                $amount = round($item['amount'], 2);
                $result[] = [
                    'category_id' => $item['category_id'],
                    'name' => $category_name . '(' . $amount . ')',
                    'value' => $amount
                ];
            }
        }
        $pie = [
            'show' => !empty($result),
            //'show' => false,
            'type' => 'pie',
        ];
        $pie['option'] = [
            'legend' => [
                'show' => true,
                'position' => "bottom",
                'float' => 'left'
            ],
            'extra' => [
                'pie' => [
                    'activeOpacity' => 1,
                    'border' => false
                ]
            ]
        ];
        $pie['series'] = [
            [
                'data' => $result
            ]
        ];
        return $pie;
    }

    //收支类型统计饼图
    private function get_pie_amount_type_data($where)
    {
        $model = new Cashflows();
        $data = $model->data_list_nopage($where, 'sum(amount) as amount,amount_type', '', 'amount_type');
        $result = [];
        if ($data) {
            foreach ($data as $item) {
                $amount = round($item['amount'], 2);
                if (empty($item['amount_type'])) {
                    $item['amount_type'] = '未分类';
                }
                $result[] = [
                    'category_id' => $item['amount_type'],
                    'name' => $item['amount_type'] . '(' . $amount . ')',
                    'value' => $amount
                ];
            }
        }
        $pie = [
            'show' => !empty($result),
            //'show' => false,
            'type' => 'pie',
        ];
        $pie['option'] = [
            'legend' => [
                'show' => true,
                'position' => "bottom",
                'float' => 'left'
            ],
            'extra' => [
                'pie' => [
                    'activeOpacity' => 1,
                    'border' => false
                ]
            ]
        ];
        $pie['series'] = [
            [
                'data' => $result
            ]
        ];
        return $pie;
    }

    //折线图
    private function get_line_data($where, $query_type)
    {
        $args = input();
        $data_type = intval($args['type'] ?? '20');
        $opts = [
            //"title" => [],
            "color" => ["#42b479"],
            "padding" => [15, 10, 0, 15],
            "enableScroll" => true,
            'dataPointShape' => false,
            "legend" => [],
            "xAxis" => [
                'disableGrid' => true,
                'type' => 'grid',
                'gridType' => 'dash',
                'itemCount' => 5,//x轴单屏显示数据的数量，默认为5个
                'scrollShow' => true,//新增是否显示滚动条，默认false
                'scrollAlign' => 'left',//滚动条初始位置
                'scrollBackgroundColor' => '#F7F7FF',//默认为 #EFEBEF
                'scrollColor' => '#DEE7F7',//默认为 #A6A6A6
            ],
            "yAxis" => [
                'gridType' => "dash",
                'dashLength' => 2,
                'showTitle' => true,
                'padding' => 10,
                'data' => [
                    ['title' => ($data_type === 10 ? '收入' : '支出') . '趋势', 'min' => 0]
                ]
            ],
            'extra' => [
                'line' => [
                    'type' => 'curve',
                    'width' => 2,
                    'activeType' => 'hollow',
                    'linearType' => "custom",
                    'onShadow' => true,
                    'animation' => "horizontal"
                ],
                'markLine' => [
                    'data' => [
                        /* [
                             'value' => 0,
                             'showLabel' => true
                         ],*/
                    ]
                ]
            ]
        ];

        $chartData = [
            'categories' => [],
            'series' => [
                [
                    'name' => $data_type == 10 ? '收入' : '支出'
                ],
            ]
        ];

        $model = new Cashflows();
        $data = $model->data_list_nopage($where, 'amount,type,date,month', 'date asc');
        if (!$data) {
            return [
                'show' => false,
                'type' => 'line',
                'option' => $opts,
                'chartData' => $chartData
            ];
        }
        $format = [];
        foreach ($data as $value) {
            if ($query_type == 'month') {
                $ftype = $value['date'];
            } else {
                $ftype = $value['month'];
            }
            if (!isset($format[$ftype][$value['type']])) {
                $format[$ftype][$value['type']] = 0;
            }
            $format[$ftype][$value['type']] += $value['amount'];
            $format[$ftype][$value['type']] = round($format[$ftype][$value['type']], 2);
        }

        foreach ($format as $key => $item) {
            if ($query_type == 'month') {
                $chartData['categories'][] = date('d日', strtotime($key));
                $chartData['series'][0]['data'][] = $item[$data_type] ?? 0;
            } else {
                $chartData['categories'][] = $key . '月';
                $chartData['series'][0]['data'][] = $item[$data_type] ?? 0;
            }
        }
        //平均值
        $avg = round(array_sum($chartData['series'][0]['data']) / count($chartData['series'][0]['data']), 2);
        $opts['extra']['markLine']['data'][] = [
            'value' => $avg,
            'showLabel' => true,
        ];

        return [
            'show' => true,
            'type' => 'line',
            'option' => $opts,
            'chartData' => $chartData
        ];
    }

    //按表格统计
    public function table_list($user_id, $args = [])
    {
        $showSet = (new User())->data_get(['user_id' => $user_id], 'show_in_amount,show_out_amount');
        $force = !empty($args['force']);
        $ckey = 'statistic_table_list_' . $user_id . md5(json_encode($args)) . md5(json_encode($showSet));
        $cache = Cache::get($ckey);
        if ($cache && !$force) {
            return self::success_return('success-cache', $cache);
        }

        $keywords = trim($args['keywords'] ?? '');
        $type = intval($args['type'] ?? 0);
        $amount_type = trim($args['amount_type'] ?? '');
        $time_type = trim($args['time_type'] ?? '');
        $year = intval($args['year'] ?? 0);
        $month = intval($args['month'] ?? 0);
        $budget_id = intval($args['budget_id'] ?? 0);
        $cashbook_id = intval($args['cashbook_id'] ?? 0);
        $where['a.user_id'] = ['a.user_id', '=', $user_id];//方便后面移除
        if ($type) {
            $where[] = ['a.type', '=', $type];
        }
        if ($budget_id) {
            $where[] = ['a.budget_id', '=', $budget_id];
        }
        if ($cashbook_id) {
            //查询所有关联用户
            $user_ids = (new PCashbookUser())->data_list_nopage(['cashbook_id' => $cashbook_id], 'user_id');
            $user_ids = array_column($user_ids, 'user_id');
            if (!in_array($user_id, $user_ids)) {
                //非法查询
                $cashbook_id = -1;//让其找不到数据
            }
            unset($where['a.user_id']);//避免不必要的麻烦
            $where[] = ['a.user_id', 'in', $user_ids];
            $where[] = ['a.cashbook_id', '=', $cashbook_id];
        }
        if ($amount_type) {
            $where[] = ['a.amount_type', '=', $amount_type === '未分类' ? '' : $amount_type];
        }
        $totalTitle = '';
        if ($year) {
            $where[] = ['a.year', '=', $year];
            $totalTitle = $year . '年';
        }
        if ($month) {
            $where[] = ['a.month', '=', $month];
            $totalTitle .= $month . '月';
        }
        if ($keywords) {
            $where[] = ['a.remark|a.amount_type|b.name', 'like', '%' . $keywords . '%'];
        }
        if ($time_type === 'range') {
            if (!empty($args['start_time'])) {
                $where[] = ['a.date', '>=', $args['start_time']];
            }
            if (!empty($args['end_time'])) {
                $where[] = ['a.date', '<=', $args['end_time']];
            }
            $totalTitle = $args['start_time'] . '至' . $args['end_time'];
        }

        //如果都空就默认三个月内
        if (empty($args['start_time']) && empty($args['end_time']) && empty($args['month']) && empty($args['year']) && empty($args['keywords']) && empty($args['type']) && empty($args['budget_id']) && empty($args['amount_type']) && empty($args['time_type'])) {
            $where[] = ['a.date', '>=', date('Y-m-d', strtotime('-3 month'))];
            $totalTitle = '最近三个月';
        }


        $fields = 'a.type,a.budget_id,a.category_id,a.amount_type,a.amount,a.year,a.month,a.day,a.date';
        $fields .= ',b.name as category_name,b.icon as category_icon';
        $model = new Cashflows();
        $data = $model->alias('a')
            ->join('categories b', 'a.category_id=b.id', 'left')
            ->field($fields)
            ->where(array_values($where))
            ->order('a.date desc')
            ->select()
            ->toArray();
        if (!$data) {
            return self::success_return('暂无数据', ['table_data' => []]);
        }

        $table_data = [
            'total' => [
                'title' => $totalTitle . '综合计算',
                'more_text' => '',
                'th' => ['总收入', '总支出', '收支差额'],
                'td' => []
            ],
            'month' => [
                'title' => '月份收支统计',
                'more_text' => '查看图表>',
                'th' => ['月份', '收入', '支出', '差额'],
                'td' => []
            ],
            'category' => [
                'title' => '分类收支统计',
                'more_text' => '查看图表>',
                'th' => ['名称', '收入', '支出', '差额'],
                'td' => []
            ],
            'category_count' => [
                'title' => '分类使用频率TOP5',
                'more_text' => '',
                'th' => ['名称', '使用次数'],
                'td' => []
            ]
        ];
        $monthly_data = [];
        $category_data = [];
        $category_count = [];
        $total_data = [];

        foreach ($data as $row) {
            $date = $row['date'];
            $amount = $row['amount'];
            $month = date('Y-m', strtotime($date));
            $category_name = $row['category_name'];
            if (!isset($monthly_data[$month])) {
                $monthly_data[$month] = ['date' => $month, 'income' => 0, 'expense' => 0, 'difference' => 0];
            }
            if (!isset($category_data[$category_name])) {
                $category_data[$category_name] = ['name' => $category_name, 'income' => 0, 'expense' => 0, 'difference' => 0];
            }
            if (!isset($category_count[$category_name])) {
                $category_count[$category_name] = ['name' => $category_name, 'count' => 0];
            }
            if (!isset($total_data['income'])) {
                $total_data['income'] = 0;
            }
            if (!isset($total_data['expense'])) {
                $total_data['expense'] = 0;
            }
            if ($row['type'] == 10) {
                $total_data['income'] += $amount;
            } elseif ($row['type'] == 20) {
                $total_data['expense'] += $amount;
            }
            $category_count[$category_name]['count'] += 1;
            if ($row['type'] == 10) {
                $monthly_data[$month]['income'] += $amount;
                $category_data[$category_name]['income'] += $amount;
            } elseif ($row['type'] == 20) {
                $monthly_data[$month]['expense'] += $amount;
                $category_data[$category_name]['expense'] += $amount;
            }
        }
        $total_data['difference'] = $total_data['income'] - $total_data['expense'];
        $table_data['total']['td'][] = [
            ['label' => $showSet['show_in_amount'] ? bcmul($total_data['income'], 1, 2) : '***', 'class' => 'bs-red'],
            ['label' => $showSet['show_out_amount'] ? bcmul($total_data['expense'], 1, 2) : '***', 'class' => 'bs-green'],
            ['label' => $showSet['show_in_amount'] && $showSet['show_out_amount'] ? bcmul($total_data['difference'], 1, 2) : '***', 'class' => $total_data['difference'] > 0 ? 'bs-red' : 'bs-green'],
        ];

        foreach ($monthly_data as $date => $info) {
            $income = $info['income'];
            $expense = $info['expense'];
            $difference = $income - $expense;
            $table_data['month']['td'][] = [
                ['label' => $date, 'class' => ''],
                ['label' => $showSet['show_in_amount'] ? bcmul($income, 1, 2) : '***', 'class' => 'bs-red'],
                ['label' => $showSet['show_out_amount'] ? bcmul($expense, 1, 2) : '***', 'class' => 'bs-green'],
                ['label' => $showSet['show_in_amount'] && $showSet['show_out_amount'] ? bcmul($difference, 1, 2) : '***', 'class' => $difference > 0 ? 'bs-red' : 'bs-green'],
            ];
        }
        foreach ($category_data as $name => $info) {
            $income = $info['income'];
            $expense = $info['expense'];
            $difference = $income - $expense;
            $table_data['category']['td'][] = [
                ['label' => $name, 'class' => ''],
                ['label' => $showSet['show_in_amount'] ? bcmul($income, 1, 2) : '***', 'class' => 'bs-red'],
                ['label' => $showSet['show_out_amount'] ? bcmul($expense, 1, 2) : '***', 'class' => 'bs-green'],
                ['label' => $showSet['show_in_amount'] && $showSet['show_out_amount'] ? bcmul($difference, 1, 2) : '***', bcmul($difference, 1, 2), 'class' => $difference > 0 ? 'bs-red' : 'bs-green'],
            ];
        }
        foreach ($category_count as $name => $info) {
            $table_data['category_count']['td'][] = [
                ['label' => $name, 'class' => ''],
                ['label' => $info['count'], 'class' => ''],
            ];
        }
        //分类收支统计按差值排序
        if ($table_data['category']['td']) {
            array_multisort(array_column($table_data['category']['td'], 3), SORT_ASC, $table_data['category']['td']);
        }

        //分类按次数倒叙
        if ($table_data['category_count']['td']) {
            array_multisort(array_column($table_data['category_count']['td'], 1), SORT_DESC, $table_data['category_count']['td']);
            $table_data['category_count']['td'] = array_slice($table_data['category_count']['td'], 0, 5);
        }
        $result = [
            'table_data' => array_values($table_data),
            'readme' => "默认查询三个月内数据，为了隐私保护，要同时开启收入和支出配置（在首页的眼睛）后才能显示差额，未开启收入和支出，将显示【***】,此处为基础表格，要查看统计图请点击【查看图表】，为了提高性能，采用了缓存，缓存时间为5分钟，如果要查看最新数据，请下拉刷新页面",
        ];

        Cache::set($ckey, $result, 300);


        return self::success_return('success', $result);


    }

    public function calendar($user_id, $args = [])
    {
        $year = $args['year'] ?? date('Y');
        $income = [];
        $expense = [];
        $model = new Cashflows();
        $table = $model->getTable('cashflows');
        $income_sql = "SELECT DATE_FORMAT(`date`, '%Y-%m-%d') as date, SUM(amount) as amount FROM `$table` "
            . " WHERE user_id = {$user_id} AND `type` = 10 AND `year` = '{$year}' "
            . " GROUP BY date";
        $expense_sql = "SELECT DATE_FORMAT(`date`, '%Y-%m-%d') as date, SUM(amount) as amount FROM `$table` "
            . " WHERE user_id = {$user_id} AND `type` = 20 AND `year` = '{$year}' "
            . " GROUP BY date";
        $income_data = \think\facade\Db::query($income_sql);
        $expense_data = \think\facade\Db::query($expense_sql);
        foreach ($income_data as $row) {
            //判断是不是.00结尾
            if (str_ends_with($row['amount'], '.00')) {
                $row['amount'] = substr($row['amount'], 0, -3);
            }

            $income[$row['date']] = $row['amount'];
        }
        foreach ($expense_data as $row) {
            if (str_ends_with($row['amount'], '.00')) {
                $row['amount'] = substr($row['amount'], 0, -3);
            }
            $expense[$row['date']] = $row['amount'];
        }
        return self::success_return('success', [
            'income' => $income,
            'expense' => $expense,
        ]);
    }
}
